package bb.lanxing

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.MenuItem
import android.view.View
import android.widget.Button
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import bb.lanxing.activity.base.BaseViewActivity
import bb.lanxing.adapter.mine.MyPagerAdapter
import bb.lanxing.fragment.MineFragment
import bb.lanxing.fragment.base.BaseTabFragment.OnFragmentInteractionListener
import bb.lanxing.fragment.discover.DiscoverFragment
import bb.lanxing.fragment.routebook.RouteBookFragment
import bb.lanxing.fragment.sport.SportFragment
import bb.lanxing.fragment.team.TeamFragment
import bb.lanxing.manager.RemoteServiceManager
import bb.lanxing.manager.SharedManager
import bb.lanxing.model.gpx.GpxFileOperator
import bb.lanxing.util.Log
import bb.lanxing.util.pop.Inspector
import bb.lanxing.view.BiciAlertDialogBuilder
import bb.lanxing.view.dialog.CommonDialogFragment
import com.bes.sdk.utils.SettingsJsonUtils
import com.besall.allbase.common.utils.FileUtils
import com.blankj.utilcode.util.ConvertUtils
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.gyf.immersionbar.ImmersionBar
import java.io.File

class MainActivity : BaseViewActivity(), OnFragmentInteractionListener {
  private var clickBackTime: Long = 0L
  private var exitByUser = false
  private lateinit var mViewPager2: ViewPager2
  private lateinit var sportFragment: SportFragment
  private lateinit var mineFragment: MineFragment
  private lateinit var lushuFragment: RouteBookFragment

  private lateinit var mBottomNavView: BottomNavigationView

  private var mCurrentPos = TAB_SIZE - 1
  private val fragments: MutableList<Fragment> = ArrayList(TAB_SIZE)
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    //add by wangsm
    var intent = getIntent()
    if (intent != null) {
      mCurrentPos = intent.getIntExtra("curr_pos", TAB_SIZE - 1)//see ProtocolActivity
    }
    Log.d("MainActivity", " mCurrentPos:  " + mCurrentPos)
    //end by wangsm
    ImmersionBar.with(this).transparentStatusBar().statusBarDarkFont(false).init()
    init()
    App.getContext().initAppWithUIVisible()
//        requestStoragePermission()
  }

  override fun onBackPressed() {
    if (RemoteServiceManager.getInstance().isSporting()) {
      showExitAppDialog()
    } else if (popBackgroundOrExit()) {
    } else {
      this.exitByUser = true
      super.onBackPressed()
    }
  }

  private fun showExitAppDialog() {
    BiciAlertDialogBuilder(this).setMessage(R.string.main_exit_content).setNegativeButton(
      R.string.main_exit_confirm
    ) { _, _ ->
      exitByUser = true
      finish()
    }.setPositiveButton(
      R.string.main_exit_background
    ) { _, _ ->
      val intent = Intent(Intent.ACTION_MAIN)
      intent.addCategory(Intent.CATEGORY_HOME)
      startActivity(intent)
    }.setTitle(R.string.confirm).show()
  }

  private fun popBackgroundOrExit(): Boolean {
    if (System.currentTimeMillis() - this.clickBackTime < QUIT_DELAY_TIME) {
      return false
    }
    this.clickBackTime = System.currentTimeMillis()
    toast(R.string.double_click_to_exit)
    App.getContext().handler.postDelayed((Runnable {
      clickBackTime = 0L
    }), QUIT_DELAY_TIME)
    return true
  }

  private fun init() {
    mViewPager2 = findViewById(R.id.vp_view_container)
    mBottomNavView = findViewById(R.id.bottom_nav_view)

    sportFragment = SportFragment()
    mineFragment = MineFragment()
    lushuFragment = RouteBookFragment.newInstance()
    fragments.add(DiscoverFragment())
    fragments.add(sportFragment)
    fragments.add(lushuFragment)
    fragments.add(TeamFragment())
    fragments.add(mineFragment)

    val mainPagerAdapter = MyPagerAdapter(this, fragments)
    mViewPager2.adapter = mainPagerAdapter
    mViewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
      override fun onPageSelected(position: Int) {
        mBottomNavView.menu.getItem(position).isChecked = true
        disableLongTouch()
      }
    })
    mBottomNavView.setOnItemSelectedListener { item: MenuItem ->
      when (item.itemId) {
        R.id.main_nav_manual -> {
          mCurrentPos = 0
        }

        R.id.nav_sport -> {
          mCurrentPos = 1
        }

        R.id.nav_book -> {
          mCurrentPos = 2
        }

        R.id.nav_team -> {
          mCurrentPos = 3
        }

        R.id.main_nav_task -> {
          mCurrentPos = 4
        }
      }
      switchFragment()
      true
    }
    mViewPager2.isUserInputEnabled = false
    mViewPager2.setCurrentItem(mCurrentPos, false)
    mViewPager2.offscreenPageLimit = mCurrentPos
  }

  private fun disableLongTouch() {
    mBottomNavView.getChildAt(0).findViewById<View>(R.id.main_nav_task).setOnLongClickListener { true }
    mBottomNavView.getChildAt(0).findViewById<View>(R.id.nav_sport).setOnLongClickListener { true }
    mBottomNavView.getChildAt(0).findViewById<View>(R.id.nav_team).setOnLongClickListener { true }
    mBottomNavView.getChildAt(0).findViewById<View>(R.id.nav_book).setOnLongClickListener { true }
    mBottomNavView.getChildAt(0).findViewById<View>(R.id.main_nav_manual).setOnLongClickListener { true }
  }

  override fun onFragmentNewMessageRefresh(index: Int, dotNum: Int, z: Boolean) {
    if (index != 6) {
      return
    }
    // saveRedDot2SP(index, dotNum)
  }

  private fun saveRedDot2SP(i: Int, dotNum: Int) {
    when (i) {
      0 -> {
        SharedManager.getInstance().setTabRedDotCount(2, dotNum)
      }

      1 -> {
        SharedManager.getInstance().setTabRedDotCount(3, dotNum)
      }

      2 -> {
        SharedManager.getInstance().setTabRedDotCount(4, dotNum)
      }

      6 -> {
        SharedManager.getInstance().setTabRedDotCount(5, dotNum)
      }
    }
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == REQUEST_CODE_SPORT) {
      mBottomNavView.menu.getItem(mCurrentPos).isChecked = true
    }
  }

  private fun switchFragment() {
    Log.d("switchFragment mCurrentPos = $mCurrentPos")
    mViewPager2.setCurrentItem(mCurrentPos, false)
  }

  fun refreshFragmentData() {
    mineFragment.loadData()
  }

  override fun onResume() {
    super.onResume()
    Inspector.inspectRuntime(this)
//        besTest()
  }

  override fun onPause() {
    super.onPause()
    Inspector.interruptRuntime()
  }

  private fun requestStoragePermission() {
    //android 11
    //<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
      if (!Environment.isExternalStorageManager()) {
        permissionDialog()
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
          checkMulti()
        }
      }
    }
  }

  private fun doRequestStoragePermission() {
    //android 11
    //<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
      if (!Environment.isExternalStorageManager()) {
        val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
        intent.data = Uri.parse("package:$packageName")
        storageLauncher.launch(intent)
      } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
          checkMulti()
        }
      }
    }
  }

  @RequiresApi(Build.VERSION_CODES.TIRAMISU) private fun checkMulti() {
    multiPermissionLauncher.launch(
      arrayOf(
        PERMISSION_READ_MEDIA_IMAGES, PERMISSION_READ_MEDIA_AUDIO, PERMISSION_READ_MEDIA_VIDEO
      )
    )
  }

  private val storageLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()
  ) {

  }

  @RequiresApi(Build.VERSION_CODES.TIRAMISU) private val multiPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions: Map<String, Boolean> ->
    run {
      permissions.entries.forEach {
        val permissionName = it.key
        if (!it.value) {
          if (shouldShowRequestPermissionRationale(permissionName)) {
            permissionDialog()
          }
        }
      }
    }
  }

  private fun permissionDialog() {
    CommonDialogFragment(
      R.layout.dialog_storge_permission, object : CommonDialogFragment.ViewListener {
        override fun bindView(v: View, dialogFragment: DialogFragment) {
          val cancelBtn = v.findViewById<Button>(R.id.negativeBtn)
          val sureBtn = v.findViewById<Button>(R.id.positiveBtn)

          cancelBtn?.apply {
            text = getString(R.string.cancel)
            setOnClickListener {
              dialogFragment.dismissAllowingStateLoss()
            }
          }
          sureBtn?.apply {
            text = getString(R.string.confirm)
            setOnClickListener {
              dialogFragment.dismissAllowingStateLoss()
              doRequestStoragePermission()
            }
          }
        }
      }).apply {
      isCancelable = false
      setMargin(ConvertUtils.dp2px(10f))
    }.show(supportFragmentManager)
  }

  companion object {
    private const val TAB_SIZE = 5
    const val REQUEST_CODE_SPORT = 101
    const val QUIT_DELAY_TIME = 2000L

    @RequiresApi(Build.VERSION_CODES.TIRAMISU) private const val PERMISSION_READ_MEDIA_IMAGES = Manifest.permission.READ_MEDIA_IMAGES

    @RequiresApi(Build.VERSION_CODES.TIRAMISU) private const val PERMISSION_READ_MEDIA_AUDIO = Manifest.permission.READ_MEDIA_AUDIO

    @RequiresApi(Build.VERSION_CODES.TIRAMISU) private const val PERMISSION_READ_MEDIA_VIDEO = Manifest.permission.READ_MEDIA_VIDEO
  }

  private fun besTest() {
    val device_model = SettingsJsonUtils.getDeviceModel(this)
    var sn = SettingsJsonUtils.getSn(this)
    sn = "test"//暂时用这个
    val path = FileUtils.checkExternalDirectoryPathExist(
      true, device_model, sn, SettingsJsonUtils.WORKOUTS_FOLDER, "20241226190738.gpxb"
    )

    val folder = FileUtils.checkExternalDirectoryPathExist(
      false, device_model, sn, SettingsJsonUtils.WORKOUTS_FOLDER
    )

    val file = File(folder, "20241226190739.gpxb")
    if (file.exists()) {
      file.delete()
    }
    file.createNewFile()
    Log.i("besTest path = $path")
//        BesSportProcessor.TrackPointReader.readTrackPoints(path)
    val gpxPoint = GpxFileOperator.getFileList(path)
    Log.i("besTest gpxPoint = $gpxPoint")
    Log.i("besTest gpxPoint size = ${gpxPoint.size}")
    GpxFileOperator.saveGpxList(file.path, gpxPoint)
    val gpxPoint1 = GpxFileOperator.getFileList(file.path)
    Log.i("besTest gpxPoint = $gpxPoint1")
  }
}
